package com.novabluetooth.services.bluetooth2;

import java.util.List;

import com.health.R;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

/**
 * 测量界面 蓝牙2.0
 * @author nova
 *
 */
public class MeasureActivity extends Activity implements OnClickListener {

	private Button btnBack, btnStartMeasure;
	private TextView tvTitle;
	private String measureItem;
	private Context context;
	private ViewFlipper viewFlipper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.ac_measure);

		context = this;

		Bundle bundle = getIntent().getExtras();
		measureItem = bundle.getString("MeasureItem");

		initView();
		if (isServiceRunning(getApplicationContext(),
				"com.novabluetooth.services.bluetooth2.ListenService")) {
			stopService(new Intent(MeasureActivity.this, ListenService.class));
		}
	}

	private void initView() {

		btnBack = (Button) findViewById(R.id.public_top_btnBack);
		btnBack.setOnClickListener(this);
		btnStartMeasure = (Button) findViewById(R.id.btn_startMeasure);
		btnStartMeasure.setOnClickListener(this);
		tvTitle = (TextView) findViewById(R.id.public_top_tvTitle);

		viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);

		int[] imgs = null;
		if (measureItem.equals("NOVABT")) { // 血氧仪相关
			tvTitle.setText("血氧仪测量参考说明");
			imgs = new int[] { R.drawable.ac_measure_bt01,
					R.drawable.ac_measure_bt02, R.drawable.ac_measure_bt03 };

		} else if (measureItem.equals("NOVABG")) { // 血糖仪相关
			tvTitle.setText("血糖仪测量参考说明");
			imgs = new int[] { R.drawable.ac_measure_bt01,
					R.drawable.ac_measure_bt02, R.drawable.ac_measure_bt03 };
		} else if (measureItem.equals("NOVATF")) { // 耳温枪相关
			tvTitle.setText("耳温枪测量参考说明");
			imgs = new int[] { R.drawable.ac_measure_bt01,
					R.drawable.ac_measure_bt02, R.drawable.ac_measure_bt03 };
		} else if (measureItem.equals("NOVATZ")) { // 耳温枪相关
			tvTitle.setText("体重计测量参考说明");
			imgs = new int[] { R.drawable.ac_measure_bt01,
					R.drawable.ac_measure_bt02, R.drawable.ac_measure_bt03 };
		}else if (measureItem.equals("NOVANJ")) { // 尿机相关
			tvTitle.setText("尿机测量参考说明");
			imgs = new int[] { R.drawable.ac_measure_bt01,
					R.drawable.ac_measure_bt02, R.drawable.ac_measure_bt03 };
		}else if(measureItem.equals("NOVAHB")){
			tvTitle.setText("血红蛋白测量参考说明");
			imgs = new int[] { R.drawable.ac_measure_bt01,
					R.drawable.ac_measure_bt02, R.drawable.ac_measure_bt03 };
		}
		for (int i = 0; i < imgs.length; i++) {
			ImageView iv = new ImageView(this);
			iv.setImageResource(imgs[i]);
			iv.setScaleType(ImageView.ScaleType.FIT_XY);
			viewFlipper.addView(iv, new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT));
		}
		AutoFlip.start();
	}

	@Override
	public void onClick(View v) {

		Intent intent = new Intent();

		int id = v.getId();
		if (id == R.id.public_top_btnBack) {
			MeasureActivity.this.finish();
		} else if (id == R.id.btn_startMeasure) {
			if (!isServiceRunning(getApplicationContext(),
					"com.novabluetooth.services.bluetooth2.ListenService")) {
				System.out.println("开始测量，ListenService没有运行，开启服务");
				startService(new Intent(MeasureActivity.this,
						ListenService.class));
			}
			final Dialog dialog = new Dialog(MeasureActivity.this,
					R.style.dialog);
			// dialog.setOnCancelListener(onCancelListener);
			dialog.setCanceledOnTouchOutside(false);
			dialog.setCancelable(false);
			flags = true;
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View view = inflater.inflate(R.layout.progressdialog, null);
			dialog.setContentView(view);
			ImageView imageView1,
			imageView2,
			imageView3,
			imageView4,
			imageView5;
			imageView1 = (ImageView) dialog
					.findViewById(R.id.progress_imageview1);
			imageView2 = (ImageView) dialog
					.findViewById(R.id.progress_imageview2);
			imageView3 = (ImageView) dialog
					.findViewById(R.id.progress_imageview3);
			imageView4 = (ImageView) dialog
					.findViewById(R.id.progress_imageview4);
			imageView5 = (ImageView) dialog
					.findViewById(R.id.progress_imageview5);
			Button btnStopMeasure = (Button) dialog
					.findViewById(R.id.btn_stopMeasure);
			btnStopMeasure.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					dialog.dismiss();
					setBluetoothViewVisible(true);
					if (isServiceRunning(getApplicationContext(),
							"com.novabluetooth.services.bluetooth2.ListenService")) {
						stopService(new Intent(MeasureActivity.this,
								ListenService.class));
						
						MeasureActivity.this.finish();
					}
				}
			});
			imageView = new ImageView[] { imageView1, imageView2, imageView3,
					imageView4, imageView5 };
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub

					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					while (flags) {
						handler.sendEmptyMessage(10);
						try {
							Thread.sleep(300);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					flags = true;
				}
			}).start();
			dialog.show();
			Toast.makeText(MeasureActivity.this, "蓝牙接口已开启，等待设备测量...",
					Toast.LENGTH_SHORT).show();
		}
	}

	private boolean isRun = true;
	Thread AutoFlip = new Thread() {

		public void run() {
			while (isRun) {
				try {
					Thread.sleep(2000);
					Message msg = new Message();
					msg.what = SHOW_NEXT;
					handler.sendMessage(msg);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					isRun = false;
					e.printStackTrace();
				}
			}
		}
	};

	ImageView[] imageView;
	int i = 1;
	int SHOW_NEXT = 1;
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			if (msg.what == 10) {

				imageView[i].setImageDrawable(context.getResources()
						.getDrawable(R.drawable.progress_image2));
				imageView[(i + 5 - 1) % 5]
						.setImageDrawable(context.getResources().getDrawable(
								R.drawable.progress_image1));
				i++;
				i = (i + 5) % 5;
			}
			if (msg.what == SHOW_NEXT) {
				showNextView();
			}

			super.handleMessage(msg);
		}

	};

	public void showNextView() {

		Animation lInAnim = AnimationUtils.loadAnimation(this,
				R.anim.push_left_in); // ���󻬶�������Ľ���Ч��alpha 0.1 -> 1.0��
		Animation lOutAnim = AnimationUtils.loadAnimation(this,
				R.anim.push_left_out); // ���󻬶��Ҳ໬���Ľ���Ч��alpha 1.0 -> 0.1��
		viewFlipper.setInAnimation(lInAnim);
		viewFlipper.setOutAnimation(lOutAnim);
		viewFlipper.showNext();

	}

	boolean flags;
	OnCancelListener onCancelListener = new OnCancelListener() {

		@Override
		public void onCancel(DialogInterface dialog) {
			// TODO Auto-generated method stub
			flags = false;
			dialog.dismiss();
			setBluetoothViewVisible(true);
			if (isServiceRunning(getApplicationContext(),
					"com.novabluetooth.services.bluetooth2.ListenService")) {
				stopService(new Intent(MeasureActivity.this,
						ListenService.class));
			}
			System.out.println("cancel!!!!");
		}
	};

	// 蓝牙服务判断
	public static boolean isServiceRunning(Context context, String serviceName) {
		boolean isRunning = false;
		ActivityManager am = (ActivityManager) context
				.getSystemService(ACTIVITY_SERVICE);
		List<RunningServiceInfo> infos = am.getRunningServices(500);
		for (RunningServiceInfo info : infos) {
			if (info.service.getClassName().equals(serviceName)) {
				Log.e("LeeTag", "服务已经运行");
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (isServiceRunning(getApplicationContext(),
				"com.novabluetooth.services.bluetooth2.ListenService")) {
			stopService(new Intent(MeasureActivity.this, ListenService.class));
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:

			MeasureActivity.this.finish();
			break;
		}
		return false;
	}

	/**
	 * 设置测量结果是否显示
	 * 
	 * @param flag
	 */
	public void setBluetoothViewVisible(boolean flag) {
		SharedPreferences sp = this.getSharedPreferences("user", MODE_PRIVATE);
		sp.edit().putBoolean("BluetoothView", flag).commit();
	}

	/**
	 * 获取测量结果是否显示
	 */
	public boolean getBluetoothViewVisible() {
		SharedPreferences sp = this.getSharedPreferences("user", MODE_PRIVATE);
		return sp.getBoolean("BluetoothView", true);
	}
}
